﻿using System;
using System.IO;
using System.Xml.Serialization;
using SalaryReport.Core.Events;

namespace SalaryReport.Core
{
    public class Templates : INotify
    {
        private const string fileName = "templates.dat";

        private readonly XmlSerializer serializer;

        public TemplatesData Data { get; set; }

        public Templates()
        {
            serializer = new XmlSerializer(typeof(TemplatesData));
        }

        public event EventHandler<SalaryArgs> OnNotify;

        public void Notify(SalaryArgs args)
        {
            if (OnNotify != null)
            {
                OnNotify(this, args);
            }
        }

        public void Save()
        {
            try
            {
                using (var stream = File.Create(fileName))
                {
                    serializer.Serialize(stream, Data);
                }
            }
            catch (Exception ex)
            {
                Notify(new SalaryArgs(ex.Message + ((ex.InnerException == null) ? string.Empty : ex.InnerException.Message)));
            }
        }

        public void Load()
        {
            try
            {
                if (File.Exists(fileName))
                {
                    using (var stream = File.OpenRead(fileName))
                    {
                        Data = (TemplatesData)serializer.Deserialize(stream);
                    }
                }
                else
                {
                    Data = new TemplatesData {PaymentTemplate = string.Empty, PrePaymentTemplate = string.Empty};
                }
            }
            catch (Exception ex)
            {
                Notify(new SalaryArgs(ex.Message + ((ex.InnerException == null) ? string.Empty : ex.InnerException.Message)));
            }
        }
    }
}